import React, {useEffect} from 'react';
import {setRouteGuard} from '@/utils/navigation';
import { useSelector } from 'react-redux';
import { RootState } from '@/stores';

export function RouteGuard({children}: {children: React.ReactNode}) {
  const token = useSelector((state: RootState) => state.user.token);
  console.log('RouteGuard')
  useEffect(() => {
    // 设置路由守卫
    setRouteGuard({
      beforeEach: async (to, from) => {
        console.log('beforeEach');
        console.log(to);
        console.log(from);

        // 需要登录才能访问的页面
        const authPages = ['/loan/ocr', '/loan/record'];

        // 如果是需要登录的页面，但用户未登录
        if (authPages.some(page => to.startsWith(page)) && !token) {
          console.log('未登录');
          // 重定向到登录页
          return '/auth/login';
        }

        // 如果已登录，但访问登录页
        if (to.startsWith('/auth/login') && token) {
          // 重定向到首页
          return '/home';
        }
        return true;
      },
      afterEach: (to, from) => {
        // 页面访问统计
        console.log('路由变化:', {to, from});
      },
    });
  }, []);

  return <>{children}</>;
}

export default RouteGuard;
